﻿package net.wangit.adm.variables;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.TreeFactory;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class VariablesTreeFactory extends TreeFactory {

	private static final Log log = LogFactory
			.getLog(VariablesTreeFactory.class);
	private static final String LINK_PREFIX = "/adm/variable.do?m=e&variable.vid=";
	private static final String ROOT_ATTRIBUTE = "oncontextmenu=showRootMenu()";
	private static final String ATTRIBUTE = "oncontextmenu=showMenu()";
	private static final String SQL = "select vid,parentid,vname,vvalue,o from AVARIABLES order by o,vid";

	public VariablesTreeFactory() {
	}

	public Tree createTree(String treeDoamin) throws Exception {
		DB db = DBFactory.getDB();
		MapList data = db.query(VariablesTreeFactory.SQL);
		if (Checker.isEmpty(data))
			return null;
		int rootRowIndex = data.findRowIndex("parentid", "");
		if (rootRowIndex < 0)
			rootRowIndex = data.findRowIndex("parentid", null);
		if (rootRowIndex < 0) {
			log.error("could not found the root of variables");
			return null;
		} else {
			Tree tree = getTree(data, rootRowIndex);
			tree.setAttribute(VariablesTreeFactory.ROOT_ATTRIBUTE);
			return tree;
		}
	}

	private Tree getTree(MapList data, int index) throws Exception {
		Tree tree = new Tree();
		Row row = data.getRow(index);
		String id = row.get("vid");
		String name = row.get("vname");
		String value = row.get("vvalue", "");
		if (value.length() > 10) {
			value = (new StringBuilder(String.valueOf(value.substring(0, 10))))
					.append("...").toString();
		}
		tree.setId(id);
		if ("".equals(value)) {
			name = new StringBuilder(name).append(" (").append(id).append(")")
					.toString();
		} else {
			name = new StringBuilder(name).append(" (").append(id).append("=")
					.append(formatValue(value)).append(")").toString();
		}
		tree.setName(name);
		tree.setAttribute(VariablesTreeFactory.ATTRIBUTE);
		tree.setAction((new StringBuilder(VariablesTreeFactory.LINK_PREFIX))
				.append(id).toString());
		for (int i = 0; i < data.size(); i++) {
			String parent = data.getRow(i).get("parentid");
			if (id.equals(parent)) {
				tree.add(getTree(data, i));
			}
		}

		return tree;
	}

	private String formatValue(String value) {
		value = value.replaceAll("<", "&lt;");
		value = value.replaceAll(">", "&gt;");
		value = value.replaceAll("\r\n", "");
		value = value.replaceAll("\r", "");
		value = value.replaceAll("\n", "");
		return value;
	}

}
